//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {


    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        let sky = this.createBitmapByName("bg_jpg");
        this.addChild(sky);
        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;
        sky.width = stageW;
        sky.height = stageH;

        let topMask = new egret.Shape();
        topMask.graphics.beginFill(0x000000, 0.5);
        topMask.graphics.drawRect(0, 0, stageW, 172);
        topMask.graphics.endFill();
        topMask.y = 33;
        this.addChild(topMask);

        let icon: egret.Bitmap = this.createBitmapByName("egret_icon_png");
        this.addChild(icon);
        icon.x = 26;
        icon.y = 33;

        let line = new egret.Shape();
        line.graphics.lineStyle(2, 0xffffff);
        line.graphics.moveTo(0, 0);
        line.graphics.lineTo(0, 117);
        line.graphics.endFill();
        line.x = 172;
        line.y = 61;
        this.addChild(line);


        let colorLabel = new egret.TextField();
        colorLabel.textColor = 0xffffff;
        colorLabel.width = stageW - 172;
        colorLabel.textAlign = "center";
        colorLabel.text = "Hello Egret";
        colorLabel.size = 24;
        colorLabel.x = 172;
        colorLabel.y = 80;
        this.addChild(colorLabel);

        let textfield = new egret.TextField();
        this.addChild(textfield);
        textfield.alpha = 0;
        textfield.width = stageW - 172;
        textfield.textAlign = egret.HorizontalAlign.CENTER;
        textfield.size = 24;
        textfield.textColor = 0xffffff;
        textfield.x = 172;
        textfield.y = 135;
        this.textfield = textfield;

        let button = new eui.Button();
        button.label = "login!";
        button.horizontalCenter = 0;
        button.verticalCenter = -100;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk 显示 登录 pop
            this.jsCallOc({methed: "SDKShowLogin",username:"123456",password:"67548"})
        }, this);

        button = new eui.Button();
        button.label = "registe!";
        button.horizontalCenter = 0;
        button.verticalCenter = -50;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk 显示 注册 pop
            this.jsCallOc({methed: "SDKShowRegiste",username:"123456",password:""})
        }, this);

        button = new eui.Button();
        button.label = "兑换!";
        button.horizontalCenter = 0;
        button.verticalCenter = 0;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk 显示 兑换 pop
            this.jsCallOc({methed: "SDKShowExchange",username:"123456",diamondNum:9991,name:"手套",price:333,tips:"钻石余额足够,test"})
        }, this);

        button = new eui.Button();
        button.label = "实名!";
        button.horizontalCenter = 0;
        button.verticalCenter = 50;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk 显示 实名 pop
            this.jsCallOc({methed: "SDKShowRealName",username:"123456"})
        }, this);

        button = new eui.Button();
        button.label = "个人中心!";
        button.horizontalCenter = 0;
        button.verticalCenter = 100;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            //zk 显示个人中心 实名 pop
            this.jsCallOc({methed: "SDKShowUserPop",username:"123456",phoneNumber:"15361695215"})
        }, this);

        button = new eui.Button();
        button.label = "toast!";
        button.horizontalCenter = 0;
        button.verticalCenter = 150;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk toast
            this.jsCallOc({methed:"SDKShowToast",msg:"json"})
        }, this);

        //关闭所有弹窗
        button = new eui.Button();
        button.label = "关闭pop!";
        button.horizontalCenter = 0;
        button.verticalCenter = 200;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk toast
            this.jsCallOc({methed:"SDKClosePop",msg:"json"})
        }, this);

        //显示球
        button = new eui.Button();
        button.label = "球!";
        button.horizontalCenter = 0;
        button.verticalCenter = 250;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk toast
            this.jsCallOc({methed:"SDKShowBall",msg:"json"})
        }, this);

        //隐藏球
        button = new eui.Button();
        button.label = "隐藏球!";
        button.horizontalCenter = 0;
        button.verticalCenter = 300;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            // //zk toast
            this.jsCallOc({methed:"SDKHiddenBall",msg:"json"})
        }, this);

        button = new eui.Button();
        button.label = "个人中心2!";
        button.horizontalCenter = 0;
        button.verticalCenter = 350;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
            //zk 显示个人中心 实名 pop
            this.jsCallOc({methed: "SDKShowUserPop",username:"123456"})
        }, this);

        let self = this
        // 登录 点击回掉
        egret.ExternalInterface.addCallback("SDKShowLoginCallBack", function (message:string) {
            console.log("zk SDKShowLoginCallBack: " + message); //forKeys:@[@"username", @"password"，@“agreeCheck”]];
            self.jsCallOc({methed:"SDKShowToast",msg:"登录校验"})
        });
        // 注册 点击回掉
        egret.ExternalInterface.addCallback("SDKShowRegisteCallBack", function (message:string) {
            console.log("zk SDKShowRegisteCallBack: " + message);//forKeys:@[@"username", @"password" ， @“agreeCheck”]];
            self.jsCallOc({methed:"SDKShowToast",msg:"注册校验"})
        });
        // 兑换 点击回掉
        egret.ExternalInterface.addCallback("SDKShowExchangeCallBack", function (message:string) {
            console.log("zk SDKShowExchangeCallBack: " + message);
            // @{
            //     @"username":self.userAccountTextField.text,
            //     @"diamondNum":self.userDiamondTextField.text,
            //     @"name":self.goodsNameTextField.text,
            //     @"price":self.goodsPriceTextField.text
                
            // }
            self.jsCallOc({methed:"SDKShowToast",msg:"兑换校验"})
        });
        // 实名 点击回掉
        egret.ExternalInterface.addCallback("SDKShowRealNameCallBack", function (message:string) {
            console.log("zk SDKShowRealNameCallBack: " + message);//forKeys:@[@"username", @"name",@"cardId"]];
            self.jsCallOc({methed:"SDKShowToast",msg:"实名校验"})
        });
        // 绑定手机 点击回掉
        egret.ExternalInterface.addCallback("SDKBindPhoneCallBack", function (message:string) {
            console.log("zk SDKBindPhoneCallBack: " + message);

            self.jsCallOc({methed:"SDKShowToast",msg:"绑定手机校验"})
        });
        // 获取验证码 点击回掉
        egret.ExternalInterface.addCallback("SDKClickGetCodeCallBack", function (message:string) {
            console.log("zk SDKClickGetCodeCallBack: " + message); // “phoneNumber”

            self.jsCallOc({methed:"SDKShowToast",msg:"获取验证码校验"})
            self.jsCallOc({methed:"SDKShowBindPoneTimer",count:30}) // 展示倒计时
            // self.jsCallOc({methed:"SDKStopBindPoneTimer"})          // 隐藏倒计时
        });
        // 退出登录 点击回掉
        egret.ExternalInterface.addCallback("SDKExitCallBack", function (message:string) {
            console.log("zk SDKExitCallBack: " + message);

            self.jsCallOc({methed:"SDKShowToast",msg:"退出"})
        });
        // 球 点击回掉
        egret.ExternalInterface.addCallback("SDKBallClickCallBack", function (message:string) {
            console.log("zk SDKBallClickCallBack: " + message);

            self.jsCallOc({methed:"SDKShowToast",msg:"球点击"})
            self.jsCallOc({methed:"SDKClosePop",msg:"json"})
            self.jsCallOc({methed:"SDKStopBindPoneTimer"})          // 隐藏倒计时
        });

        // egret.ExternalInterface.call("sendToNative", "zk message from JS");
    }
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: Array<any>): void {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }

    /**
     * 点击按钮
     * Click the button
     */
    private jsCallOc(data:any) {
        let param = JSON.stringify(data)
        console.log("zk jsCallOc: param=",param);
        
        egret.ExternalInterface.call("callFromJs", param);

        // // //zk 显示 登录 pop
        // egret.ExternalInterface.call("SDKShowLogin", "json");
        // // //zk 显示 注册 pop
        // egret.ExternalInterface.call("SDKShowRegiste", "json");
        // // //zk 显示 兑换 pop
        // egret.ExternalInterface.call("SDKShowExchange", "json");
        // // //zk 显示 实名 pop
        // egret.ExternalInterface.call("SDKShowRealName", "json");
        // //zk 显示个人中心 实名 pop
        // egret.ExternalInterface.call("SDKShowUserPop", "json");
        // // //zk 显示个人中心 实名 pop
        // egret.ExternalInterface.call("SDKShowToast", "json");
    }
}
